<template>
    <!-- 加工验收-新增 -->
    <div class="e-form">
        <BillTop @cancel="handleClose"></BillTop>
        <div class="tabs">
            <div class="tabs-title">基本信息</div>
            <div style="width: 100%" class="form">
                <el-form
                    :model="formData"
                    label-width="150px"
                    ref="formDataRef"
                    :rules="formDataRules"
                >
                    <el-row>
                        <el-col :span="12" v-if='isRedSingle'>
                            <el-form-item label="验收编号" prop="billNo">
                                    {{ formData.billNo }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="所属机构" prop="orgName">
                                {{ formData.orgName }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="收料类型" prop="receivingType">
                                <el-radio-group
                                    v-model="formData.receivingType"
                                    :disabled='isRedSingle'
                                >
                                    <el-radio :label="0">普通加工</el-radio>
                                    <el-radio :label="1">砼加工</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="验收日期"
                                prop="acceptanceDate"
                            >
                                <el-date-picker
                                    v-model="formData.acceptanceDate"
                                    type="date"
                                    placeholder="选择日期"
                                    value-format="yyyy-MM-dd"
                                    :clearable="false"
                                    v-if='!isRedSingle'
                                >
                                </el-date-picker>
                                <span v-else>{{formData.acceptanceDate}}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item
                                label="是否计加工费"
                                prop="isIncludingProcessingFee"
                            >
                                <el-radio-group
                                    v-model="formData.isIncludingProcessingFee"
                                    :disabled='isRedSingle'
                                >
                                    <el-radio :label="1">是(外部加工)</el-radio>
                                    <el-radio :label="0">否(自行加工)</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-if='isRedSingle'>
                            <el-form-item label="采购人员" prop="purchaserName">
                                {{ formData.purchaserName }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12" v-if='isRedSingle'>
                            <el-form-item
                                label="加工单位"
                                prop="processingUnitName"
                            >
                                <!-- <el-input
                                    v-model="formData.processingUnitName"
                                    readonly
                                    v-if='!isRedSingle'
                                >
                                    <i
                                        slot="suffix"
                                        class="
                                            el-input__icon
                                            el-icon-document-copy
                                        "
                                        @click="processingUnitNameClick"
                                    ></i>
                                </el-input> -->
                                <span>{{formData.processingUnitName}}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <!-- 是否计加工费的值为: 是(外部加工,才显示该字段) -->
                            <el-form-item
                                label="加工合同"
                                v-show="formData.isIncludingProcessingFee && isRedSingle"
                            >
                                <!-- <el-input
                                    v-model="formData.contractName"
                                    readonly
                                    v-if='!isRedSingle'
                                >
                                    <i
                                        slot="suffix"
                                        class="
                                            el-input__icon
                                            el-icon-document-copy
                                        "
                                        @click="contractNoClick"
                                    ></i>
                                </el-input> -->
                                <span>
                                    {{formData.contractName}}
                                    <i
                                        slot="suffix"
                                        class="
                                            el-input__icon
                                            el-icon-document-copy
                                        "
                                        @click="contractNoClick"
                                        v-if='formData.contractName'
                                    ></i>
                                </span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12" v-if='isRedSingle'>
                            <el-form-item label="税率%" prop="taxRate">
                                <!-- <el-input
                                    placeholder="请填写"
                                    v-model="formData.taxRate"
                                    @input.native="onInput0_100"
                                    v-enterFloat
                                    v-if='!isRedSingle'
                                ></el-input> -->
                                <span>{{formData.taxRate}}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="验收人员"
                                prop="acceptancerName"
                            >
                                <el-input
                                    v-model="formData.acceptancerName"
                                    readonly
                                    v-if='!isRedSingle'
                                >
                                    <i
                                        slot="suffix"
                                        class="
                                            el-input__icon
                                            el-icon-document-copy
                                        "
                                        @click="acceptancerNameClick"
                                    ></i>
                                </el-input>
                                <span v-else>{{formData.acceptancerName}}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if='isRedSingle'>
                        <el-col :span="12">
                            <!-- 汇总验收明细的清单税额累计 -->
                            <el-form-item label="税额" prop="taxAmount">
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.taxAmount"
                                    v-if='!isRedSingle'
                                    v-enter-float="{
                                        set: formData,
                                        key: 'taxAmount'
                                    }"
                                ></el-input>
                                <span v-else>{{formData.taxAmount}}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="服务费用(元)" prop="">
                                {{ formData.freight }}
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="12">
                            <!-- 收料类型为【普通加工】显示“原材料来源” -->
                            <el-form-item
                                label="原材料来源"
                                :prop="
                                    !formData.receivingType
                                        ? 'sourceOfRawMaterials'
                                        : 'sourceOfRawMaterialss'
                                "
                                v-show="!formData.receivingType"
                            >
                                <el-radio-group
                                    v-model="formData.sourceOfRawMaterials"
                                    :disabled='isRedSingle'
                                >
                                    <el-radio :label="1">购买</el-radio>
                                    <el-radio :label="2">自有</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-if='isRedSingle'>
                            <el-form-item
                                label="加工验收金额(元)"
                                prop="acceptanceAmount"
                            >
                                {{ formData.acceptanceAmount }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12" v-if='isRedSingle'>
                            <el-form-item label="税价合计" prop="totalAmount">
                                <!-- <el-input
                                    placeholder="请填写"
                                    v-model="formData.totalAmount"
                                ></el-input> -->
                                {{ formData.totalAmount }} 元
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-if='isRedSingle'>
                            <el-form-item label="币种" prop="currencyId">
                                <!-- <el-select
                                    v-model="formData.currencyId"
                                    placeholder="请选择"
                                    v-if="!formData.isIncludingProcessingFee && !isRedSingle"
                                    @change="currencyChange"
                                >
                                    <el-option
                                        v-for="item in currencyForm"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    >
                                    </el-option>
                                </el-select> -->
                                <span>{{ formData.currency }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if='isRedSingle'>
                        <el-col :span="12">
                            <el-form-item label="本位币" prop="baseCurName">
                                {{ formData.baseCurName }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="本位币汇率" prop="baseCurRate">
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.baseCurRate"
                                    v-enter-float2="{
                                        set: formData,
                                        key: 'baseCurRate'
                                    }"
                                    v-if='!isBaseCurRate && !isRedSingle'
                                    @blur="baseCurRateBlur"
                                ></el-input>
                                <span v-else>{{formData.baseCurRate}}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <!-- <el-col :span="12" v-show='isRedSingle'>
                            <el-form-item
                                label="验收金额(本位币)"
                                prop="baseCurAcceptanceAmount"
                            >
                                {{ formData.baseCurAcceptanceAmount }}
                            </el-form-item>
                        </el-col> -->
                        <el-col :span="12">
                            <el-form-item label="状态" prop="state">
                                {{ showState(formData.state) }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12" v-if='isRedSingle'>
                            <el-form-item label="传财务共享" prop="">
                                {{ formData.easId ? '已传' : '未传'}}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-if="isRedSingle">
                            <el-form-item label="冲红单"
                                ><span :style="redBillStateStyle">{{
                                    redBillStateFun
                                }}</span></el-form-item
                            >
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-form-item label="备注">
                            <el-input
                                v-model="formData.remarks"
                                type="textarea"
                                :rows="2"
                                resize="none"
                                placeholder="请输入内容"
                                maxlength='500'
                            >
                            </el-input>
                        </el-form-item>
                    </el-row>
                </el-form>
            </div>
        </div>
        <div class="buttons">
            <el-button type="primary" style="background: #2e61d7" @click="save"
                >保存</el-button
            >
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations, mapState } from 'vuex'
import { formatDate, showLoading, hideLoading, openAppClient } from '@/utils/common'
import proAccRequest from '@/api/materials/processingAcceptance'

export default {
    data () {
        return {
            //表单数据
            formData: {
                billNo: '', //验收编号
                orgName: '', //所属机构
                isIncludingProcessingFee: 1, //是否计加工费
                acceptanceDate: formatDate(new Date(), 'yyyy-MM-dd'), //验收日期
                receivingType: 0, //收料类型
                purchaserName: '', //采购人员
                processingUnitName: '', //加工单位
                acceptancerName: '', //验收人员
                taxRate: '', //税率%
                freight: 0, //运输单位费用
                taxAmount: '', //税额
                currency: '', //币种
                acceptanceAmount: '', //加工验收金额
                showEas: '', //传财务共享
                totalAmount: '', //税价合计
                baseCurAcceptanceAmount: '', //验收金额(本位币)
                baseCurName: '', //本位币
                state: 0, //状态
                remarks: '', //备注
                acceptanceQuantity: 0,
                acceptancerId: '',
                baseCurFreight: 0,
                baseCurId: '',
                baseCurRate: '',
                baseCurTaxAmount: 0,
                baseCurTotalAmount: 0,
                billId: '',
                businessType: 0,
                currencyId: '',
                easId: '',
                founderId: '',
                founderName: '',
                gmtCreate: '',
                gmtModified: '',
                invoiceNo: '',
                isAccepSettle: true,
                isRed: 0,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                purchaserId: '',
                purchasingUnitId: '',
                purchasingUnitName: '',
                redBillState: '',
                rmbAcceptanceAmount: 0,
                rmbFreight: 0,
                rmbId: '',
                rmbName: '',
                rmbRate: 0,
                rmbTaxAmount: 0,
                rmbTotalAmount: 0,
                settleId: '',
                settleNo: '',
                sourceBillId: '',
                sourceBillNo: '',
                sourceId: '',
                sourceNumber: '',
                supplierId: '',
                supplierName: '',
                workId: '',
                contractId: '',
                contractName: '',
                contractNo: '',
                processingUnitId: '',
                sourceOfRawMaterials: 1
            },
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            formDataRules: {
                // billNo: [{ required: true, message: '请输入税率', trigger: 'blur' }],
                // orgName: [{required: true, message: '请输入税率', trigger: 'blur'}],
                receivingType: [
                    {
                        required: true,
                        message: '请选择收料类型',
                        trigger: 'blur'
                    }
                ],
                // acceptanceDate: [
                //     {
                //         required: true,
                //         message: '请选择验收日期',
                //         trigger: 'blur'
                //     }
                // ],
                isIncludingProcessingFee: [
                    {
                        required: true,
                        message: '请选择是否计加工费',
                        trigger: 'blur'
                    }
                ],
                // purchaserName: [
                //     {
                //         required: true,
                //         message: '采购人员是必填项',
                //         trigger: 'blur'
                //     }
                // ],
                // processingUnitName: [
                //     {
                //         required: true,
                //         message: '请选择加工单位',
                //         trigger: 'blur'
                //     }
                // ],
                // taxRate: [
                //     {
                //         required: true,
                //         message: '请填写税率',
                //         trigger: 'blur'
                //     }
                // ],
                taxAmount: [
                    {
                        required: true,
                        message: '请填写税额',
                        trigger: 'blur'
                    }
                ],
                // acceptanceAmount: [
                //     {
                //         required: true,
                //         message: '加工验收金额为必填项',
                //         trigger: 'blur'
                //     }
                // ],
                // totalAmount: [
                //     {
                //         required: true,
                //         message: '请填写税价合计',
                //         trigger: 'blur'
                //     }
                // ],
                // currencyId: [
                //     {
                //         required: true,
                //         message: '请选择币种',
                //         trigger: 'blur'
                //     }
                // ],
                // baseCurName: [
                //     {
                //         required: true,
                //         message: '本位币为必填项',
                //         trigger: 'blur'
                //     }
                // ],
                // baseCurRate: [
                //     {
                //         required: true,
                //         message: '请填写本位币汇率',
                //         trigger: 'blur'
                //     }
                // ],
                // baseCurAcceptanceAmount: [
                //     {
                //         required: true,
                //         message: '验收金额(本位币)为必填项',
                //         trigger: 'blur'
                //     }
                // ],
                sourceOfRawMaterials: [
                    {
                        required: true,
                        message: '请选择原材料来源',
                        trigger: 'blur'
                    }
                ]
            },
            isBaseCurRate: true,
            processingUnited: {
                materials: [],
                processingUnitId: ''
            },
            isRedSingle: false,
            redFormData: null,
            redBillStateStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '',
                'text-align': 'center'
            },
        }
    },
    computed: {
        ...mapState({
            options: state => state.contract.ctClassify,
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm //币种
        }),
        // //状态
        // statusLable () {
        //     return param => {
        //         const state = this.$store.state.settlementManagement.ysState
        //         const obj = state.find(x => x.value == param)
        //         return obj ? obj.label : ''
        //     }
        // },
        // 红单状态
        redBillStateFun () {
            let redState = ''
            switch (this.formData.redBillState) {
            case 0:
                redState = '冲销中'
                break
            case 1:
                redState = '冲销中'
                break
            case 2:
                redState = '已冲销'
                break
            case 3:
                redState = '红单'
                break
            }
            return redState
        }

    },
    watch: {
        'formData.receivingType' () {
            // 如果收料类型为【普通加工】,原材料来源必选, 如果收料类型为【砼加工】,则非必选,并清除提示信息
            if (this.formData.receivingType) {
                this.$refs.formDataRef.clearValidate('sourceOfRawMaterials')
                this.formData.sourceOfRawMaterials = ''
            }
        },
        // 本位币和币种一样的时候，值为1；不一样的时候，填写正数，不能为0，保留4位小数
        'formData.currency' () {
            if (this.formData.currency == this.formData.baseCurName) {
                this.isBaseCurRate = true
                this.formData.baseCurRate = 1
            } else {
                this.isBaseCurRate = false
                this.formData.baseCurRate = null
            }
        },
        // // 监听验收金额
        // 'formData.acceptanceAmount' () {
        //     // 税价合计 = 验收金额 + 税额
        //     this.formData.totalAmount = +this.formData.acceptanceAmount + +this.formData.taxAmount
        //     // 验收金额(本位币) = 验收金额 * 本位币汇率
        //     this.formData.baseCurAcceptanceAmount = +this.formData.acceptanceAmount * +this.formData.baseCurRate
        // },
        // // 监听税额
        // 'formData.taxAmount' () {
        //     // 税价合计 = 验收金额+税额
        //     this.formData.totalAmount = +this.formData.acceptanceAmount + +this.formData.taxAmount
        // },
        'formData.redBillState' () {
            if (this.formData.redBillState == 3) {
                this.redBillStateStyle.backgroundColor = '#FF2300'
            } else if (
                this.formData.redBillState == 0 ||
                this.formData.redBillState == 1
            ) {
                this.redBillStateStyle.backgroundColor = '#FFA40D'
            } else if (this.formData.redBillState == 2) {
                this.redBillStateStyle.backgroundColor = 'rgb(153,153,153)'
            }
        }
    },
    components: {},
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.formData.orgName = data.userInfo.orgInfo.orgName
        this.formData.acceptancerId = this.userInfo.userId
        this.formData.acceptancerName = localStorage.getItem('userName')
        const { baseCyByOrgId } = this.userInfo
        this.formData.baseCurName = baseCyByOrgId.currencyName //本位币
        this.formData.baseCurId = baseCyByOrgId.currency
        this.$route.query.isRedSingle === '1'
            ? (this.isRedSingle = true)
            : (this.isRedSingle = false)
        if (this.isRedSingle) {
            this.getRedList()
        }
    },
    mounted () {},
    beforeDestroy () {},
    methods: {
        ...mapMutations(['setPopConfirm']),

        // 如果是点击冲红单进入的新增页,则需要返显数据,只有备注能修改,其余均不能修改
        async getRedList () {
            showLoading()
            try {
                let data = await proAccRequest.redSingle(this.$route.query.billid)
                this.redFormData = this._.cloneDeep(data)
                data.currency = this.currencyForm.find(
                    x => x.value === data.currencyId
                ).label

                this.formData = data
            } finally {
                hideLoading()
            }
        },
        // 点击加工单位后面的选择源单
        async processingUnitNameClick () {
            let data = await proAccRequest.selectSource(
                {
                    receivingType: this.formData.receivingType
                },
                this.processingUnited
            )
            Object.assign(
                this.$data.processingUnited,
                this.$options.data().processingUnited
            )
            this.formData.processingUnitName = data[0].processingUnitName // 加工单位
            this.formData.processingUnitId = data[0].processingUnitId // 加工单位Id
            this.formData.contractName = data[0].contractName // 加工合同
            this.formData.purchaserName = data[0].purchasingPersonnelName // 采购人员名称

            // this.formData.taxRate = data[0] // 税率,根据加工收料带入加工合同税率
            // this.formData.currency = data[0] // 币种

            data.forEach(item => {

                this.processingUnited.materials.push({
                    materialClassId: item.materialClassId
                        .split('/')
                        .slice(1, 3)
                        .join('/'),
                    materialId: item.materialId,
                    texture: item.texture
                })

            })
            this.processingUnited.processingUnitId =
                this.formData.processingUnitId

        },
        // 点击选择验收人员
        async acceptancerNameClick () {
            let data = await proAccRequest.institutionalStaff()
            this.formData.acceptancerId = data[0].userId
            this.formData.acceptancerName = data[0].userName
        },
        // 税率只能输入0-100的数
        onInput0_100 (e) {
            this.$message.closeAll()
            if (e.target.value < 0 || e.target.value > 100) {
                this.$message.warning('只能输入[0,100]区间的数')
            }
            e.target.value =
                (e.target.value >= 0 &&
                    e.target.value <= 100 &&
                    e.target.value.match(/^\d{1,3}(\.\d*)?$/)[0]) ||
                null
        },
        // 本位币汇率不能为0
        baseCurRateBlur () {
            if (this.formData.baseCurRate == 0) {
                this.formData.baseCurRate = null
            }
            this.formData.baseCurAcceptanceAmount =
                +this.formData.acceptanceAmount * +this.formData.baseCurRate
        },
        // 当币种切换时,获取人民币汇率
        currencyChange (val) {
            this.formData.currency = this.currencyForm.find(
                x => x.value === val
            ).label //币种名称
        },
        contractNoClick () {
            // 弹出合同详细页面
            openAppClient(`/processingContractApplyShow?billid=${this.formData.contractId}&isview=${true}`, '加工合同查看')
        },
        //保存按钮
        save () {
            this.$refs.formDataRef.validate(valid => {
                if (!valid) return false
                proAccRequest
                    .saveProcessingAcceptanceAdd(this.formData)
                    .then(res => {
                        this.clientPop(
                            'info',
                            '保存成功,是否继续',
                            () => {
                                this.$router.replace({
                                    path: '/processCheckEdit',
                                    query: {
                                        billid: res,
                                        name: 'receivingMaterials'
                                    }
                                })
                            },
                            null,
                            this.handleClose
                        )
                    })
            })
        },
        //取消按钮
        handleClose () {
            this.$router.push('/processCheck')
        },
        showState (state) {
            const _state = this.$store.state.settlementManagement.ysState
            const obj = _state.find(x => x.value === Number(state))
            return obj.label
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}

.el-tab-pane {
    margin-left: -10px;
}
</style>
